import axios from 'axios'
import { Message } from 'element-ui'
import router from '../router'

// 请求拦截器
axios.interceptors.request.use(config => {
    // 如果存在token，则让后续每个接口都携带token
    if (window.sessionStorage.getItem("token")) {
        config.headers['Authorization'] = window.sessionStorage.getItem("token")
    }
    return config;
},error => {
    Message.error("请求失败")
})


//响应拦截器
axios.interceptors.response.use(success => {
    //接口请求成功，对信息进行处理，后端返回状态码可能为500，401，403
    //success.status是前端请求后端接口是否成功的状态码
    if (success.status || success.status == 200) {
        if (success.data.code == 500 || success.data.code == 401 || success.data.code == 403) {
            Message.error({message:success.data.message})
            return ;
        }
        if (success.data.message) {
            Message.success({message:success.data.message})
        }
        return success.data;
    }
},error => {
    // error : 接口访问失败
    //error.response.code : 响应码

    if (error.response.code == 504 || error.response.code == 404) {
        Message.error("服务器被吃了")
    }else if (error.response.code == 401) {
        Message.error("尚未登录，请登录")
        router.replace("/")
    }else if (error.response.code == 403) {
        Message.error("权限不足，请联系管理员")
    }else {
        console.log("返回信息" + error);
        if (error.response.data.message) {
            Message.error({message:error.response.data.message})
            return;
        }else {
            Message.error({message:'服务器错误'})

        }
    }
    return;
})

// 基本的路径。如：/cms、/pay等
let base = ''


// 传送json格式的post请求
export const postRequest = (url,params) => {
    return axios({
        method : 'post',
        url: `${base}${url}`,
        data:params
    })
}



export const getRequest = (url,params) => {
    return axios({
        method : 'get',
        url: `${base}${url}`,
        data:params
    })
}

export const deleteRequest = (url,params) => {
    return axios({
        method : 'delete',
        url: `${base}${url}`,
        data:params
    })
}

export const putRequest = (url,params) => {
    return axios({
        method : 'put',
        url: `${base}${url}`,
        data:params
    })
}

